package cn.xiehang.SoundSight;

import android.app.AlertDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

public class ShoppingFragment extends Fragment {
    private static final String ARG_PRODUCT_ID = "product_id";
    private Product product;

    private String productId;
    private ImageView ivProductImage;
    private TextView tvProductName, tvProductPrice, tvProductDescription,addToCartBadge;
    private Button btnAddToCart, btnBuyNow;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (getArguments() != null) {
//            productId = getArguments().getString(ARG_PRODUCT_ID);
//        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局文件
        View view = inflater.inflate(R.layout.fragment_shopping, container, false);

        if (product == null) {
            return view; // 提前返回，避免空指针
        }
        // 初始化控件
        ivProductImage = view.findViewById(R.id.product_image);

        tvProductName = view.findViewById(R.id.product_name);

        tvProductPrice = view.findViewById(R.id.product_price);

        tvProductDescription = view.findViewById(R.id.product_description);

        addToCartBadge = view.findViewById(R.id.add_to_cart_button_badge);

        btnBuyNow = view.findViewById(R.id.buy_button);

        if (product.getBuyCount()>0) {
            addToCartBadge.setVisibility(View.VISIBLE);
            addToCartBadge.setText(String.valueOf(product.getBuyCount()));
        } else {
            addToCartBadge.setVisibility(View.INVISIBLE);
        }

        Glide.with(this)
                .load(product.getImageUrl())
                .into(ivProductImage);
        tvProductName.setText(product.getName());
        tvProductPrice.setText(String.valueOf(product.getPrice())+"元");
        tvProductDescription.setText(product.getIntroduction());


        btnBuyNow = view.findViewById(R.id.buy_button);
        btnAddToCart = view.findViewById(R.id.add_to_cart_button);
        btnAddToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理添加到购物车的逻辑
                int buyCount = AddToCart();
                if (buyCount == 0) {
                    Toast.makeText(requireContext(),"添加失败", Toast.LENGTH_SHORT).show();
                    return; // 如果没有添加成功，则提前返回
                }
                addToCartBadge.setVisibility(View.VISIBLE);
                addToCartBadge.setText(String.valueOf(buyCount));


            }
        });

        btnBuyNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理立即购买的逻辑
                int buyCount = AddToCart();
                if (buyCount == 0) {
                    Toast.makeText(requireContext(),"添加失败", Toast.LENGTH_SHORT).show();
                    return; // 如果没有添加成功，则提前返回
                }
                // 获取宿主 Activity
                FragmentActivity activity = getActivity();
                if (activity != null) {
                    // 执行 Fragment 切换
                    FragmentManager fm=activity.getSupportFragmentManager();
                    FragmentTransaction transaction = fm.beginTransaction();
                    //隐藏所有的Fragment
                    for (Fragment frag : fm.getFragments()) {
                        if (frag != null && frag.isAdded()) {
                            transaction.hide(frag);
                        }
                    }
                    Fragment existingFragment = fm.findFragmentByTag("ShoppingCartFragment");

                    if (existingFragment != null) {
                        //从存储信息中更新
                        ((CartFragment) existingFragment).reClick();
                        transaction.show(existingFragment);
                    } else {
                        Fragment shoppingCartFragment = new CartFragment();
                        transaction.add(R.id.FragmentContainer, shoppingCartFragment, "ShoppingCartFragment");
                    }
                    transaction.commit();
                }
            }
        });
        return view;
    }

    private int AddToCart() {
        // 1. 获取 SharedPreferences


        //获取用户姓名
        SharedPreferences sharedPref = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE);
        //如果没有获取到用户名和密码，则提示用户登录
        if (sharedPref.getString("username", null) == null || sharedPref.getString("password", null) == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
            builder.setTitle("提示")
                    .setMessage("请先登录")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 关闭对话框
                        dialog.dismiss();
                    })
                    .show();
            return 0;
        }
        String username = sharedPref.getString("username", null);

        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("cart"+username, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        // 2. 获取现有的购物车列表（如果有）
        String cartJson = sharedPreferences.getString("cart_items", "[]");
        Gson gson = new Gson();
        Type type = new TypeToken<List<Product>>() {}.getType();
        List<Product> cartItems = gson.fromJson(cartJson, type);
        int buyCount = 0;

        // 2. 检查是否已存在相同商品
        boolean found = false;
        for (Product item : cartItems) {
            if (item.getId()==product.getId()) {
                item.setBuyCount(item.getBuyCount() + 1); // 数量 +1
                buyCount = item.getBuyCount();
                found = true;
                break;
            }
        }

        // 3. 如果不存在，添加新商品并设置数量为 1
        if (!found) {
            product.setBuyCount(1);
            buyCount = product.getBuyCount();
            cartItems.add(product);
        }

        // 4. 保存更新后的购物车
        String updatedCartJson = gson.toJson(cartItems);
        sharedPreferences.edit()
                .putString("cart_items", updatedCartJson)
                .apply();

//        Toast.makeText(requireContext(), "已添加到购物车，数量为"+buyCount, Toast.LENGTH_SHORT).show();
        return buyCount;
    }
    public void setProduct(Product product) {
        this.product = product;
    }

    public void setText() {
        Glide.with(this)
                .load(product.getImageUrl())
                .into(ivProductImage);
        tvProductName.setText(product.getName());
        tvProductPrice.setText(String.valueOf(product.getPrice())+"元");
        tvProductDescription.setText(product.getIntroduction());
        if (product.getBuyCount()>0) {
            addToCartBadge.setVisibility(View.VISIBLE);
            addToCartBadge.setText(String.valueOf(product.getBuyCount()));
        } else {
            addToCartBadge.setVisibility(View.INVISIBLE);
        }
    }

    // 模拟加载商品详情（实际开发中应该使用 Retrofit/Room 等）
//    private void loadProductDetails(String productId) {
//        // 这里只是示例，实际应该根据 ID 查询数据库或 API
//        String details = "商品详情（ID=" + productId + "）\n\n"
//                + "名称：示例商品\n"
//                + "价格：¥99.99\n"
//                + "库存：100\n"
//                + "描述：这是一个示例商品，用于演示 Fragment 传参。";
//
//        tvProductDetails.setText(details);
//    }
}